package com.controller.sys;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.common.Const;
import com.common.Result;
import com.config.captcha.CaptchaConfig;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 验证码
 * 生成验证码和key，存储在redis中，用户登录传回key和验证码，进行校验
 */
@RestController
public class CaptchaController extends BaseController {

    @Autowired
    private CaptchaConfig captchaConfig;

    //图片验证码
    @Autowired
    private Producer producer;

    @GetMapping("/captcha")
    public Result captcha() throws IOException {
        //生成uuidKey
        String key = UUID.randomUUID().toString();
        //验证码生成
        String code = producer.createText();
        //生成图片
        BufferedImage image = producer.createImage(code);
        //字节流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        //图片写入字节流
        ImageIO.write(image, "jpg", byteArrayOutputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,"; //base64默认前缀
        String base64Img = str + encoder.encode(byteArrayOutputStream.toByteArray());

        //存到redis中
        redisService.hset(Const.CAPTCHA_KEY, key, code, 12000);

        return Result.success(
                MapUtil.builder()
                        .put("key", key)
                        .put("captchaImg", base64Img)
                        .build()
        );
    }
}
